/*!
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *    Author: flareguner
 *    E-Mail: flareguner@gmail.com
 *    Years: 2010-2010
 */


#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtGui/QTextDocumentFragment>
#include <QtCore/QEventLoop>
#include <QtCore/QStringList>
#include <QtCore/QDebug>

#include "3rdparty/qxtjson/qxtjson.h"
#include "translate.h"



static const QStringList lang_short_list =
        QStringList()
  <<"sq"  <<"ar"  <<"bg"  <<"ca"
  <<"zh-CN"   <<"zh-TW"   <<"hr"
  <<"cs"  <<"da"  <<"nl"  <<"en"
  <<"et"  <<"tl"  <<"fi"  <<"fr"
  <<"gl"  <<"de"  <<"el"  <<"iw"
  <<"hi"  <<"hu"  <<"id"  <<"it"
  <<"ja"  <<"ko"  <<"lv"  <<"lt"
  <<"mt"  <<"no"  <<"pl"  <<"pt"
  <<"ro"  <<"ru"  <<"sr"  <<"sk"
  <<"sl"  <<"es"  <<"sv"  <<"th"
  <<"tr"  <<"uk"  <<"vi";

static const QStringList lang_full_list =
        QStringList()
  <<"Albanian"  <<"Arabic"  <<"Bulgarian"  <<"Catalan"
  <<"Chinese (Simplified)"   <<"Chinese (Traditional)"   <<"Croatian"
  <<"Czech"  <<"Danish"  <<"Dutch"  <<"English"
  <<"Estonian"  <<"Filipino"  <<"Finnish"  <<"French"
  <<"Galician"  <<"German"  <<"Greek"  <<"Hebrew"
  <<"Hindi"  <<"Hungarian"  <<"Indonesian"  <<"Italian"
  <<"Japanese"  <<"Korean"  <<"Latvian"  <<"Lithuanian"
  <<"Maltese"  <<"Norwegian"  <<"Polish"  <<"Portuguese"
  <<"Romanian"  <<"Russian"  <<"Serbian"  <<"Slovak"
  <<"Slovenian"  <<"Spanish"  <<"Swedish"  <<"Thai"
  <<"Turkish"  <<"Ukrainian"  <<"Vietnamese";

static const int sample_words_count = 20;


Translate::Translate(QObject *parent) :
    QObject(parent)
{
}

QString Translate::translate(const QString &src, const QString &dest, const QString &txt){
    QByteArray html = txt.toUtf8();

    html.replace("&", "&amp;");
    html.replace("<", "&lt;");
    html.replace(">", "&gt;");
    html.replace("\n", "<br>");

    QByteArray query = "v=1.0&format=html";
    query += "&langpair=" + src.toLatin1() + "%7C" + dest.toLatin1();
    query += "&q=" + html.toPercentEncoding();

    QUrl url("http://mymemory.translated.net/api/get");
    QNetworkRequest req(url);
    req.setRawHeader("User-Agent", "Mozilla/5.0");
    req.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    req.setRawHeader("Content-Length", QByteArray::number(query.size()));

    QNetworkAccessManager manager;
    QEventLoop loop;

    connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));

    QNetworkReply *reply  = manager.post(req, query);
    loop.exec();

    const QByteArray rawdata = reply->readAll();

    QxtJSON parser;


    QVariantMap map = parser.parse(QString::fromUtf8(rawdata.data())).toMap();
    QVariantMap map2 = map["responseData"].toMap();

    const QString result = map2["translatedText"].toString();

    return QTextDocumentFragment::fromHtml(result).toPlainText();
}

QStringList Translate::getCodes() const {
    return lang_short_list;
}

QStringList Translate::getNames() const {
    return lang_full_list;
}


int Translate::getLanguageIndex(const QString &sample){
    /*const */QString detected = detectLanguage(sample);


    int index = 0;
    for(int i = 0; i  < lang_short_list.size(); i++){
        if(lang_short_list.at(i) == detected){
            index = i;
            break;
        }
    }

//    const int index = langmap[detected];
    qDebug() << Q_FUNC_INFO << index << detected;
    return index;
}

QString Translate::detectLanguage(const QString text){
    const QStringList words_list = text.split(' ');
    const int words_count = words_list.size() > sample_words_count ?
                            sample_words_count :
                            words_list.size();

    QString sample;
    for(int i = 0; i < words_count; i++)
        sample.append(words_list.at(i) + ' ');

    qDebug() << Q_FUNC_INFO << sample;

    QUrl url("http://ajax.googleapis.com/ajax/services/language/detect");
    QList<QPair<QString, QString> > query;
    query << QPair<QString, QString>("v", "1.0");
    query << QPair<QString, QString>("q", sample);
    url.setQueryItems(query);

    QNetworkAccessManager manager;
    QEventLoop loop;

    connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));

    QNetworkRequest req(url);
    req.setRawHeader("User-Agent", "Mozilla/5.0");
    QNetworkReply *reply  = manager.get(req);
    loop.exec();

    const QByteArray rawdata = reply->readAll();

    QxtJSON parser;

    QVariantMap map = parser.parse(rawdata.data()).toMap();
    QVariantMap map2 = map["responseData"].toMap();

    const QString result = map2["language"].toString();
   return result;
}
